<?php

namespace app\admin\model;

use think\Model;
use think\Db;
use traits\model\SoftDelete;

class ProjectAssess extends Model
{

    use SoftDelete;

    

    // 表名
    protected $name = 'project_assess';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [

    ];

    public function base($query)
    {
        $query->alias('project_assess')->where('project_assess.caijiakuid',CAIJIAKU_ID)->useSoftDelete('project_assess.'.$this->deleteTime);
    }
    
    public static function init()
    {
        self::beforeInsert(function ($row) {
            $row->caijiakuid = CAIJIAKU_ID;
        });
    }

    public function project()
    {
        return $this->belongsTo('Project', 'project_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    
    public function admin()
    {
        return $this->belongsTo('app\admin\model\Admin', 'admin_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function importFormal($data, $adminid, $es)
    {
        if (empty($data)) return ['status' => 0, 'msg' => '没有需要导入的数据'];
        $insertData = [];
        $updateData = [];
        //获取项目信息
        $projectList = Project::where('id', 'in', array_unique(array_column($data, 'project_id')))->column('project_name,pricing_date', 'id');
        $queryModel = new \app\common\model\caijiatong\PriceQuery($es);
        foreach ($data as $key => $value) {
            if (!empty($value['isimport'])) continue;
            $projectInfo = $projectList[$value['project_id']] ?? [];
            if (empty($projectInfo)) continue;
            $updateData[] = [
                'id' => $value['id'],
                'isimport' => 1,
                'import_adminid' => $adminid,
                'import_time' => time(),
            ];
            $year = date('Y', strtotime($projectInfo['pricing_date']));
            $row =[
                'caijiakuid' => $value['caijiakuid'],
                'admin_id' => $adminid,
                'project_name' => $projectInfo['project_name'],
                'title' => $value['name'],
                'own_spec' => $value['description'],
                'unit' => $value['unit'],
                'price' => $value['unit_price'],
                'tax' => $value['tax'],
                'showdate' => $projectInfo['pricing_date'],
                // 'brandname' => $value['brandname'],
                // 'suppliername' => $value['suppliername'],
                'catename' => $value['catename'],
                'project_id' => $value['project_id'],
                // 'notaxprice' => $value['unit_price'],
                'year' => $year,
                'createtime' => time(),
                'updatetime' => time(),
            ];
            //判断主库是否已存在
            $where = [
                'project_name' => $row['project_name'],
                'title' => $row['title'],
                'own_spec' => $row['own_spec'],
                'unit' => $row['unit'],
                'price' => $row['price'],
            ];
            $exist = Db::name('material_inventory')->where($where)->count();
            if ($exist) {
                continue;
            }
            //查询材价通价格
            $esdata = $this->getESPriceData($row, $queryModel);
            $row = array_merge($row, $esdata);
            $insertData[] = $row;
        }
        if (empty($insertData)) return ['status' => 0, 'msg' => '没有需要导入的数据或数据已存在'];
        try{
            $this->startTrans();
            $updateRes = $this->allowField(true)->saveAll($updateData);
            $insertRes = Db::name('material_inventory')->insertAll($insertData);
            if (!$updateRes || !$insertRes) {
                $this->rollback();
                return ['status' => 0, 'msg' => '导入失败'];
            }
            $this->commit();
            return ['status' => 1, 'msg' => '导入成功'];
        } catch (\Exception $e) {
            $this->rollback();
            return ['status' => 0, 'msg' => $e->getMessage()];
        }
    }

    protected function getESPriceData($params, $queryModel)
    {
        $re = $queryModel->getPriceQuery($params);
        $data = [];
        $data['faxprice'] = !empty($re['fax']['list']) ? (float)$re['fax']['list'][0]['_source']['taxmarketprice'] : 0;
        $data['faxnum'] = $re['fax']['count'] ?? 0;
        $data['mixprice'] = !empty($re['mix']['list']) ? (float)$re['mix']['list'][0]['_source']['taxmarketprice'] : 0;
        $data['mixnum'] = $re['mix']['count'] ?? 0;
        $data['inquiryprice'] = !empty($re['inquiry']['list']) ? (float)$re['inquiry']['list'][0]['_source']['return'] : 0;;
        $data['inquirynum'] = $re['inquiry']['count'] ?? 0;
        $data['govprice'] = !empty($re['gov']['list']) ? (float)$re['gov']['list'][0]['_source']['govtaxprice'] : 0;;
        $data['govnum'] = $re['gov']['count'] ?? 0;
        //获取分类
        $data['material_id'] = !empty($re['fax']['list']) ? $re['fax']['list'][0]['_source']['material_id'] : 1208;
        $data['material_name'] = !empty($re['fax']['list']) ? $re['fax']['list'][0]['_source']['materialname'] : '其他材料';
        return $data;
    }

}
